package com.guigu.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.erp.dto.ManufactureProceduringDto;
import com.guigu.erp.pojo.*;
import com.guigu.erp.service.*;
import com.guigu.erp.utils.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RequestMapping("/manufacture/procedure")
@Controller
public class ManufactureProceduringController {
    @Autowired
    private ManufactureManufactureService manufactureManufactureService;

    @Autowired
    private ManufactureProcedureService manufactureProcedureService;

    @Autowired
    private ManufactureProcedureModuleService manufactureProcedureModuleService;

    @Autowired
    private ManufactureProceduringService manufactureProceduringService;

    @Autowired
    private ManufactureProcedureModulingService manufactureProcedureModulingService;

    @Autowired
    private StorageCellService storageCellService;

    @Autowired
    private NumberUtils numberUtils;

    @Autowired
    private DesignFileService designFileService;

    @Autowired
    private StorageGatherService storageGatherService;

    @Autowired
    private StorageGatherDetailsService storageGatherDetailsService;

    @RequestMapping("addProductionRecords")
    @ResponseBody
    public boolean addProductionRecords(@RequestBody ManufactureProceduringDto dto) {
        System.out.println(dto);
        //取出派工单编号 根据派工单编号查询生产总表和生产工序表
        String manufactureId = dto.getManufactureId();
        QueryWrapper<ManufactureManufacture> wrapper = new QueryWrapper<>();
        wrapper.eq("MANUFACTURE_ID", manufactureId);
        //生产总表对象
        ManufactureManufacture manufacture = manufactureManufactureService.getOne(wrapper);
        //根据生产总表id查询生产工序表
        QueryWrapper<ManufactureProcedure> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PARENT_ID", manufacture.getId());
        queryWrapper.eq("PROCEDURE_NAME", dto.getProcedureName());
        //生产工序表对象
        ManufactureProcedure procedure = manufactureProcedureService.getOne(queryWrapper);

        //添加生产工序过程记录
        ManufactureProceduring proceduring = new ManufactureProceduring();
        //设置父级序号
        proceduring.setParentId(manufacture.getId());
        //设置工序序号
        proceduring.setDetailsNumber(procedure.getDetailsNumber());
        //设置工序编号
        proceduring.setProcedureId(procedure.getProcedureId());
        //设置工序名称
        proceduring.setProcedureName(procedure.getProcedureName());
        //设置本次工时数
        proceduring.setLabourHourAmount(dto.getThisHour());
        //设置单位工时成本
        proceduring.setCostPrice(procedure.getCostPrice());
        //设置工时成本小计
        BigDecimal total = new BigDecimal(0);
        List<ManufactureProcedureModule> details = dto.getDetails();
        for (int i = 0; i < details.size(); i++) {
            BigDecimal temp = details.get(i).getThisCount().multiply(details.get(i).getCostPrice());
            total = total.add(temp);
        }
        proceduring.setSubtotal(total);
        //设置登记次数
        proceduring.setRegCount(procedure.getDetailsNumber());
        //设置负责人
        proceduring.setProcedureResponsiblePerson(dto.getProcedureResponsiblePerson());
        //设置登记人
        proceduring.setRegister(dto.getRegister());
        //设置登记时间
        proceduring.setRegisterTime(dto.getRegisterTime());
        //调用添加的方法
        manufactureProceduringService.save(proceduring);
        //添加生产工序物料过程记录
        //取出dto里面的生产工序物料明细对象
        List<ManufactureProcedureModule> list = dto.getDetails();
        //循环添加
        for (int i = 0; i < list.size(); i++) {
            ManufactureProcedureModuling moduling = new ManufactureProcedureModuling();
            //添加父级序号
            moduling.setParentId(proceduring.getId());
            //设置本工序物料序号
            moduling.setDetailsNumber(i + 1);
            //设置产品编号
            moduling.setProductId(list.get(i).getProductId());
            //设置产品名称
            moduling.setProductName(list.get(i).getProductName());
            //设置单位物料成本
            moduling.setCostPrice(list.get(i).getCostPrice());
            //设置本次使用数量
            moduling.setAmount(list.get(i).getThisCount());
            //设置物料成本小计
            moduling.setSubtotal(moduling.getAmount().multiply(moduling.getCostPrice()));
            //调用添加的方法
            manufactureProcedureModulingService.save(moduling);
        }

        //修改生产工序表 工序完成标志 实际工时数
        //设置实际工时数
        procedure.setRealLabourHourAmount(procedure.getRealLabourHourAmount().add(dto.getThisHour()));
        //设置实际物料成本
        procedure.setRealModuleSubtotal(procedure.getRealModuleSubtotal().add(total));
        //设置实际工时成本
        procedure.setRealSubtotal(procedure.getRealSubtotal().add(procedure.getLabourHourAmount().multiply(procedure.getSubtotal())));
        //设置工序标志
        int flag = -1;
        for (int i = 0; i < details.size(); i++) {
            ManufactureProcedureModule module = details.get(i);
            BigDecimal temp = module.getThisCount().add(module.getRealAmount());

            if(module.getAmount().compareTo(temp)==0) {
                flag = i;
            }
        }
        if (flag != -1) {
            procedure.setProcedureFinishTag("G004-1");
            //设置工序交接标志
            procedure.setProcedureTransferTag("G005-0");
            //修改生产总表的生产过程标志
            manufacture.setManufactureProcedureTag("S002-1");
            manufactureManufactureService.updateById(manufacture);
        } else {
            procedure.setProcedureFinishTag("G004-2");
            //设置工序交接标志
            procedure.setProcedureTransferTag("G005-0");
            //修改生产总表的生产过程标志
            manufacture.setManufactureProcedureTag("S002-0");
            manufactureManufactureService.updateById(manufacture);
        }

        for (int i = 0; i < details.size(); i++) {
            ManufactureProcedureModule module = details.get(i);
            module.setRealAmount(module.getRealAmount().add(module.getThisCount()));

            module.setRealSubtotal(module.getRealSubtotal().add(module.getCostPrice().multiply(module.getRealAmount())));
            manufactureProcedureModuleService.updateById(module);

        }
        //修改生产工序物料表

        //修改
        boolean flags = manufactureProcedureService.updateById(procedure);



        return flags;
    }

    @RequestMapping("updRecords")
    @ResponseBody
    public boolean updRecords(@RequestBody ManufactureProceduringDto dto) {
        //取出派工单编号 根据派工单编号查询生产总表和生产工序表
        String manufactureId = dto.getManufactureId();
        QueryWrapper<ManufactureManufacture> wrapper = new QueryWrapper<>();
        wrapper.eq("MANUFACTURE_ID", manufactureId);
        //生产总表对象
        ManufactureManufacture manufacture = manufactureManufactureService.getOne(wrapper);
        //根据生产总表id查询生产工序表
        QueryWrapper<ManufactureProcedure> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PARENT_ID", manufacture.getId());
        queryWrapper.eq("PROCEDURE_NAME", dto.getProcedureName());
        //生产工序表对象
        ManufactureProcedure procedure = manufactureProcedureService.getOne(queryWrapper);

        //修改总表状态
        manufacture.setManufactureProcedureTag("S002-0");
        manufactureManufactureService.updateById(manufacture);
        //判断是否完成
//        List<ManufactureProcedureModule> list = dto.getDetails();
//        int flag = -1;
//        for (int i = 0; i < list.size(); i++) {
//            if (list.get(i).getAmount().compareTo(list.get(i).getRealAmount()) == 0) {
//                flag = i;
//            }
//        }
//        if (flag != -1) {
            procedure.setProcedureFinishTag("G004-3");
            //设置工序交接标志
            procedure.setProcedureTransferTag("G005-1");
//        } else {
//            procedure.setProcedureFinishTag("G004-2");
//            //设置工序交接标志
//            procedure.setProcedureTransferTag("G005-0");
//        }
//
        boolean b = manufactureProcedureService.updateById(procedure);
        return b;
    }

    @RequestMapping("upd")
    @ResponseBody
    public boolean upd(BigDecimal realAmount,Integer pid){
        ManufactureProcedure procedure = manufactureProcedureService.getById(pid);
        procedure.setRealAmount(realAmount);
        procedure.setProcedureTransferTag("G005-1");
        ManufactureManufacture manufacture = manufactureManufactureService.getById(procedure.getParentId());
        manufacture.setManufactureProcedureTag("S002-1");
        manufactureManufactureService.updateById(manufacture);
        boolean b = manufactureProcedureService.updateById(procedure);

        return b;
    }

    @RequestMapping("getId")
    @ResponseBody
    public ManufactureProcedure getId(Integer id){
        ManufactureProcedure procedure = manufactureProcedureService.getById(id);
        return procedure;
    }

    @RequestMapping("updDesign")
    @ResponseBody
    public boolean updDesign(Integer realId,BigDecimal realAmount){
        //得到生产总表
        boolean b=false;
        ManufactureProcedure procedure = manufactureProcedureService.getById(realId);
        procedure.setProcedureTransferTag("G005-2");
        manufactureProcedureService.updateById(procedure);
        ManufactureManufacture manufacture = manufactureManufactureService.getById(procedure.getParentId());
        QueryWrapper<ManufactureProcedure> wrapper = new QueryWrapper<>();
        wrapper.eq("PARENT_ID",manufacture.getId());
        wrapper.eq("PROCEDURE_TRANSFER_TAG","G005-0");
        QueryWrapper<ManufactureProcedure> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("PARENT_ID",manufacture.getId());
        List<ManufactureProcedure> list1 = manufactureProcedureService.list(wrapper1);
        List<ManufactureProcedure> list = manufactureProcedureService.list(wrapper);
        int flag=-1;
        if(list.size()==0){
            flag=1;
        }else {
            flag=-1;
        }
        if (flag==1){
            for (int i=0;i<list1.size();i++){
                ManufactureProcedure manufactureProcedure = list1.get(i);
                if (manufactureProcedure.getProcedureTransferTag().equals("G005-2")){
                    //修改总表数据
                    manufacture.setManufactureProcedureTag("S002-2");
                    manufacture.setTestedAmount(realAmount);
                    manufacture.setRealModuleCostPriceSum(manufacture.getRealModuleCostPriceSum().add(manufactureProcedure.getRealModuleSubtotal()));
                    manufacture.setRealLabourCostPriceSum(manufacture.getRealLabourCostPriceSum().add(manufactureProcedure.getRealSubtotal()));
                    b= manufactureManufactureService.updateById(manufacture);
                }
            }
//            QueryWrapper<StorageCell> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("PRODUCT_ID",manufacture.getProductId());
//            StorageCell one = storageCellService.getOne(queryWrapper);
//            if(one==null){
//                StorageCell cell = new StorageCell();
//                String typeNumber = numberUtils.getTypeNumber("400");
//                //设置库存编号
//                cell.setStoreId(typeNumber);
//                //设置产品编号
//                cell.setProductId(manufacture.getProductId());
//                //设置产品名称
//                cell.setProductName(manufacture.getProductName());
//                //设置审核标志
//                cell.setCheckTag("S001-1");
//                QueryWrapper<DesignFile> fileQueryWrapper = new QueryWrapper<>();
//                fileQueryWrapper.eq("PRODUCT_ID",manufacture.getProductId());
//                DesignFile file = designFileService.getOne(fileQueryWrapper);
//                cell.setFirstKindId(file.getFirstKindId());
//                cell.setFirstKindName(file.getFirstKindName());
//                cell.setSecondKindId(file.getSecondKindId());
//                cell.setSecondKindName(file.getSecondKindName());
//                cell.setThirdKindId(file.getThirdKindId());
//                cell.setThirdKindName(file.getThirdKindName());
//                cell.setMinAmount(new BigDecimal(100));
//                cell.setMaxAmount(new BigDecimal(300));
//                cell.setMaxCapacityAmount(new BigDecimal(500));
//                cell.setAmount(new BigDecimal(0));
//                storageCellService.save(cell);
                StorageGather gather = new StorageGather();
                gather.setGatherId(numberUtils.getTypeNumber("401"));
                gather.setReason("R001-1");
                gather.setAmountSum(realAmount);
                gather.setGatheredAmountSum(realAmount);
                gather.setChecker("aa");
                gather.setRegister("bb");
                gather.setRegisterTime(new Date());
                gather.setCheckTime(new Date());
//                gather.setCostPriceSum(manufacture.getRealModuleCostPriceSum());
                gather.setCheckTag("S001-1");
                gather.setStoreTag("K002-1");
                storageGatherService.save(gather);
                StorageGatherDetails details = new StorageGatherDetails();
                details.setParentId(gather.getId());
                details.setProductId(manufacture.getProductId());
                details.setProductName(manufacture.getProductName());
                details.setAmount(realAmount);
                details.setGatherTag("K002-1");
                storageGatherDetailsService.save(details);
//            }
        }
        if (flag==-1){
            manufacture.setManufactureProcedureTag("S002-0");
            b= manufactureManufactureService.updateById(manufacture);
        }




        return b;
    }

}
